package com.ext.aic.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.ext.aic.R;
import com.ext.aic.apis.user.AuditStatusRequest;
import com.ext.aic.apis.user.PreinstalledLicenseRequest;
import com.ext.aic.beans.DeviceMeta;
import com.ext.aic.beans.params.PreinstalledLicenseParams;
import com.ext.aic.beans.response.AuditStatusResponse;
import com.ext.aic.beans.response.PreinstalledLicenseResponse;
import com.ext.aic.constants.CacheConstants;
import com.ext.aic.constants.EBusConstants;
import com.ext.aic.databinding.SplashLayoutBinding;
import com.ext.aic.enums.PreinstalledLicenseStatus;
import com.ext.aic.utils.RedirectUtils;
import com.ext.aic.utils.ToastyUtils;
import com.ext.aic.utils.UserUtils;
import com.ext.aic.utils.device.DeviceUtils;
import com.eyinfo.android_pure_utils.ebus.EBus;
import com.eyinfo.android_pure_utils.ebus.SubscribeEBus;
import com.eyinfo.android_pure_utils.executor.CycleExecutor;
import com.eyinfo.mpkv.MPLocalKV;

@SuppressLint("CustomSplashScreen")
public class SplashActivity extends BasePureActivity {

    private SplashLayoutBinding binding;
    private boolean processedState;
    private int auditStatusCount = 0;
    private boolean auditStatusChecking = false;
    private boolean isFirstCheckStatus = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = View.inflate(this, R.layout.splash_layout, null);
        binding = SplashLayoutBinding.bind(view);
        setContentView(binding.getRoot());

        bindView();
        initData();
    }

    private void bindView() {
        binding.inAppBtn.setOnClickListener(this::onInAppClick);
        hideAuditViews();
    }

    private void initData() {
        EBus.getInstance().registered(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (UserUtils.getInstance().isEnableDebugAccount()) {
            authorizationHandler.startAuthorization(this, this, this::authSuccessCallback, this::recoverAuditViews);
        } else {
            if (MPLocalKV.getInstance().getBoolean(CacheConstants.INSTALL_LICENSE_STATUS_KEY, false)) {
                authorizationHandler.startAuthorization(this, this, this::authSuccessCallback, this::recoverAuditViews);
            } else {
                isFirstCheckStatus = true;
                queryAuditStatus();
            }
        }
    }

    private void hideAuditViews() {
        binding.tipTextTv.setVisibility(View.GONE);
        binding.auditNumberEt.setVisibility(View.GONE);
        binding.checkCodeEt.setVisibility(View.GONE);
        binding.inAppBtn.setVisibility(View.GONE);
        binding.cancelTv.setVisibility(View.GONE);
        binding.progressLpi.setVisibility(View.GONE);
        binding.loadingTv.setVisibility(View.GONE);
        binding.statusTv.setVisibility(View.GONE);
    }

    private void recoverAuditViews() {
        binding.tipTextTv.setVisibility(View.VISIBLE);
        binding.auditNumberEt.setVisibility(View.VISIBLE);
        binding.checkCodeEt.setVisibility(View.VISIBLE);
        binding.inAppBtn.setVisibility(View.VISIBLE);
        binding.cancelTv.setVisibility(View.VISIBLE);
        binding.progressLpi.setVisibility(View.GONE);
        binding.loadingTv.setVisibility(View.GONE);
        binding.statusTv.setVisibility(View.GONE);
    }

    public void authSuccessCallback() {
        RedirectUtils.getInstance().startActivity(this, MainActivity.class);
    }

    public void onInAppClick(View view) {
        String auditNumber = binding.auditNumberEt.getText().toString();
        String verifyCode = binding.checkCodeEt.getText().toString();
        if (TextUtils.isEmpty(auditNumber) || TextUtils.isEmpty(verifyCode)) {
            ToastyUtils.getInstance().show(getString(R.string.audit_verify_hint));
            return;
        }
        binding.auditNumberEt.setEnabled(false);
        binding.checkCodeEt.setEnabled(false);
        binding.inAppBtn.setEnabled(false);
        binding.statusTv.setVisibility(View.VISIBLE);
        binding.statusTv.setText(R.string.audit_verifying);

        PreinstalledLicenseParams preinstalledLicenseParams = new PreinstalledLicenseParams();
        preinstalledLicenseParams.setAuditNumber(auditNumber);
        preinstalledLicenseParams.setVerifyCode(verifyCode);

        DeviceMeta deviceMeta = DeviceUtils.getInstance().getDeviceInfo(this);
        preinstalledLicenseParams.setDeviceMeta(deviceMeta);
        preinstalledLicenseParams.setDeviceSerialNumber(DeviceUtils.getInstance().getDeviceId(this));

        processedState = false;

        preinstalledLicenseRequest.request(this, this, preinstalledLicenseParams);
    }

    private PreinstalledLicenseRequest preinstalledLicenseRequest = new PreinstalledLicenseRequest() {
        @Override
        protected void onPreinstalledLicenseSuccess(PreinstalledLicenseResponse response) {
            processedState = true;
            if (TextUtils.equals(response.getStatus(), PreinstalledLicenseStatus.auditing.name())) {
                auditingCall();
            } else if (TextUtils.equals(response.getStatus(), PreinstalledLicenseStatus.pass.name())) {
                auditPass();
            } else if (TextUtils.equals(response.getStatus(), PreinstalledLicenseStatus.notPass.name())) {
                auditNotPass();
            }
        }

        @Override
        protected void onPreinstalledLicenseEnd() {
            if (!processedState) {
                binding.auditNumberEt.setEnabled(true);
                binding.checkCodeEt.setEnabled(true);
                binding.inAppBtn.setEnabled(true);
                binding.statusTv.setVisibility(View.GONE);
            }
        }
    };

    private void auditingCall() {
        binding.statusTv.setText(R.string.auditing_tip);
        cycleExecutor.start();

        queryAuditStatus();
    }

    private void queryAuditStatus() {
        if (auditStatusChecking) {
            return;
        }
        auditStatusChecking = true;
        String deviceId = DeviceUtils.getInstance().getDeviceId(this);
        auditStatusRequest.request(this, this, deviceId);
    }

    private AuditStatusRequest auditStatusRequest = new AuditStatusRequest() {
        @Override
        protected void onAuditStatusSuccess(AuditStatusResponse response) {
            if (TextUtils.equals(response.getStatus(), PreinstalledLicenseStatus.pass.name())) {
                auditPass();
            } else if (TextUtils.equals(response.getStatus(), PreinstalledLicenseStatus.notPass.name())) {
                if (isFirstCheckStatus) {
                    recoverAuditViews();
                } else {
                    auditNotPass();
                }
            } else if (isFirstCheckStatus) {
                recoverAuditViews();
            }
        }

        @Override
        protected void onAuditStatusFail() {
            if (isFirstCheckStatus) {
                recoverAuditViews();
            }
        }

        @Override
        protected void onAuditStatusEnd() {
            auditStatusChecking = false;
            auditStatusCount = 0;
        }
    };

    private void auditNotPass() {
        auditStatusChecking = true;
        cycleExecutor.stop();
        auditStatusChecking = false;
        auditStatusCount = 0;

        binding.auditNumberEt.setEnabled(true);
        binding.checkCodeEt.setEnabled(true);
        binding.inAppBtn.setEnabled(true);
        binding.statusTv.setVisibility(View.VISIBLE);
        binding.statusTv.setText(R.string.audit_not_pass);
    }

    private void auditPass() {
        MPLocalKV.getInstance().put(CacheConstants.INSTALL_LICENSE_STATUS_KEY, true);
        authorizationHandler.startAuthorization(this, this, this::authSuccessCallback, this::recoverAuditViews);
    }

    private CycleExecutor cycleExecutor = new CycleExecutor() {

        private String omit = "";

        @Override
        protected void onDoingWithMainLooper(Object params) {
            String tip = getString(R.string.auditing_tip);
            if (omit.length() < 3) {
                omit += ".";
            } else {
                omit = "";
            }
            binding.statusTv.setText(String.format("%s%s", tip, omit));

            auditStatusCount++;
            if (auditStatusCount > 5) {
                queryAuditStatus();
            }
        }
    };

    @SubscribeEBus(receiveKey = {EBusConstants.finishSplash})
    public void onFinishSplash() {
        cycleExecutor.stop();
        finish();
    }
}
